package com.atguigu.gmall.oms.service.impl;

import com.atguigu.gmall.oms.entity.OrderItemEntity;
import com.atguigu.gmall.oms.service.OrderItemService;
import com.atguigu.gmall.order.vo.OrderItemVo;
import com.atguigu.gmall.order.vo.OrderSubmitVo;
import com.google.gson.Gson;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.oms.mapper.OrderMapper;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<OrderEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<OrderEntity>()
        );

        return new PageResultVo(page);
    }
    Gson gson = new Gson();
    //需要整合分布式事务管理：
    @Transactional //本地事务
    @Override
    public OrderEntity saveOrder(Long userId, OrderSubmitVo orderSubmitVo) {
        //保存订单数据
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userId);
        orderEntity.setStatus(0);//订单待支付 0
        orderEntity.setCreateTime(new Date());
        orderEntity.setPayAmount(orderSubmitVo.getTotalPrice());//应付金额(总金额-积分抵扣金额)
        orderEntity.setTotalAmount(orderSubmitVo.getTotalPrice());
        orderEntity.setPayType(1);//默认支付宝支付
        orderEntity.setOrderSn(orderSubmitVo.getOrderToken());//订单编号
        orderEntity.setDeliveryCompany(orderSubmitVo.getDeliveryCompany());
        orderEntity.setReceiverName(orderSubmitVo.getAddress().getName());
        orderEntity.setReceiverAddress(orderSubmitVo.getAddress().getAddress());
        orderEntity.setReceiverCity(orderSubmitVo.getAddress().getCity());
        orderEntity.setReceiverPhone(orderSubmitVo.getAddress().getPhone());
        orderEntity.setGrowth(orderSubmitVo.getTotalPrice().intValue());//计算购买的商品sku 得到 总的成长积分
        orderEntity.setIntegration(orderSubmitVo.getTotalPrice().intValue());
//        orderEntity.setIntegrationAmount(); 购物积分抵扣金额
        this.save(orderEntity);
        //发票
        //优惠券使用
//        orderEntity.setAutoConfirmDay(); 用户支付成功 发货后 用户的自动确认时间
//        orderEntity.setCommentTime();
        //保存订单项到数据库
        List<OrderItemVo> orderSubmitVoItems = orderSubmitVo.getItems();
        if(!CollectionUtils.isEmpty(orderSubmitVoItems)){
            List<OrderItemEntity> itemEntityList = orderSubmitVoItems.stream().map(orderItemVo -> {
                OrderItemEntity orderItem = new OrderItemEntity();
                orderItem.setOrderId(orderEntity.getId());
                orderItem.setOrderSn(orderEntity.getOrderSn());
                orderItem.setSkuQuantity(orderItemVo.getCount());//购买数量
                orderItem.setSkuName(orderItemVo.getTitle());
                orderItem.setSkuPic(orderItemVo.getDefaultImage());
                orderItem.setSkuId(Long.parseLong(orderItemVo.getSkuId()));
                orderItem.setSkuPrice(orderItemVo.getPrice());
                orderItem.setSkuAttrsVals(gson.toJson(orderItemVo.getSaleAttrs()));
                orderItem.setRealAmount(orderItemVo.getPrice());
                //远程访问查询orderItem需要的其他数据
                //spu
//                orderItem.setSp
                return orderItem;
            }).collect(Collectors.toList());
            orderItemService.saveBatch(itemEntityList);
        }
        //订单和订单项保存成功：发送定时关单的消息
        /*
        关单时 还需要释放库存：orderToken可以查询到锁定的库存数据
         */
        rabbitTemplate.convertAndSend("order_exchange","order.close" , orderSubmitVo.getOrderToken());
        return orderEntity;
    }

}